Lambda expressions in Python are a powerful tool for writing concise and efficient code. They allow you to create anonymous functions on the fly, without the need for a formal definition.
A lambda function is defined using the lambda keyword, followed by the arguments and an expression. The expression is evaluated and returned by the function. For example, the following lambda function takes two arguments x and y, and returns their sum:
lambda x, y: x + y
This lambda function can be assigned to a variable and used like any other function:
add = lambda x, y: x + y result = add(2, 3) print(result) # Output: 5
Lambda functions are particularly useful in situations where you need to pass a function as an argument to another function. For example, the built-in sorted()
function can take a key argument that specifies a function to use for sorting. Here's an example using a lambda function to sort a list of tuples by their second element:
lst = [(1, 2), (3, 1), (2, 4)] sorted_lst = sorted(lst, key=lambda x: x[1]) print(sorted_lst) # Output: [(3, 1), (1, 2), (2, 4)]
In this example, the lambda function lambda x: x[1]
is used to specify that the second element of each tuple should be used for sorting.
Lambda functions can also be used to create closures, which are functions that remember the values of variables in their enclosing scope. For example, the following code creates a closure that remembers the value of the variable n
:
def make_adder(n): return lambda x: x + n add_five = make_adder(5) result = add_five(3) print(result) # Output: 8
In this example, the make_adder()
function returns a lambda function that takes an argument x
and adds it to the value of n
that was passed in when the closure was created.
Overall, lambda expressions are a powerful and flexible tool for writing concise and efficient code in Python. They are particularly useful when you need to pass functions as arguments, or when you want to create closures that remember values from their enclosing scope.